<template>
  <div id="api-module">
    <v-header title="API服务模块" :saveShow="false" :showDownloadBtn="false"></v-header>
    <div class="main-cont">
      <top-toolbar v-on:operate="handleToolClick" :buttonsObj="buttonsObj"></top-toolbar>
      <el-table :data="tableData.list"
                highlight-current-row
                @current-change="changeTabs"
                ref="table"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="moduleName" label="服务模块名称"></el-table-column>
        <el-table-column prop="moduleCode" label="服务模块代码"></el-table-column>
        <el-table-column prop="moduleStatus" label="状态" :formatter="transData"></el-table-column>
        <el-table-column prop="gwEnvName" label="环境"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" :formatter="transCreateTime"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="onlineApiModule(scope.row.moduleId, scope.row)">上线</el-button>
            <el-button type="text" size="mini" @click="offlineApiModule(scope.row.moduleId, scope.row)">下线</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="tableData.total">
      </el-pagination>
      <div class="tabs">
        <el-tabs v-model="activeName">
          <!--<el-tab-pane label="设置模块错误代码" name="first"></el-tab-pane>-->
          <!--<el-tab-pane label="设置模块报文头" name="second"></el-tab-pane>-->
          <el-tab-pane label="修改服务模块" name="third"></el-tab-pane>
          <el-tab-pane label="查看服务模块" name="fourth"></el-tab-pane>
        </el-tabs>
        <keep-alive v-if="aliveShow">
          <component :is="view" :Data="tabsData" :messages="messages" :opts="opts" :getwayEnvOpts="getwayEnvData.list"></component>
        </keep-alive>
      </div>
    </div>
     <!--新增服务模块-->
    <el-dialog title="新增服务模块" :visible.sync="dialogVisible" width="900px" @close="addApiModuleCancel">
      <el-form :model="modulePostData"  ref="modulePostForm" :rules="modulePostRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模块编号" prop="moduleCode" :label-width="formLabelWidth">
              <el-input v-model="modulePostData.moduleCode" placeholder="请输入模块编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块名称" prop="moduleName" :label-width="formLabelWidth">
              <el-input v-model="modulePostData.moduleName" placeholder="请输入模块名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模块版本" prop="moduleVersion" :label-width="formLabelWidth">
              <el-input v-model="modulePostData.moduleVersion" placeholder="请输入模块版本"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属网关环境" prop="gwEnvId" :label-width="formLabelWidth">
              <el-select popper-class="zIndex-popper" v-model="modulePostData.gwEnvId" placeholder="请选择所属网关环境">
                <el-option
                  v-for="item in getwayEnvData.list"
                  :key="item.gwEnvId"
                  :label="item.gwEnvName"
                  :value="item.gwEnvId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务地址" prop="serverAddress"  :label-width="formLabelWidth">
              <el-input v-model="modulePostData.serverAddress" placeholder="请输入模块版本"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务类型" prop="serverType"  :label-width="formLabelWidth">
              <el-select v-model="modulePostData.serverType" placeholder="请选择" popper-class="zIndex-popper">
                <el-option
                  v-for="item in optionsServerType"
                  :key="item.value"
                  :label="item.value"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="模块描述信息" prop="desc" :label-width="formLabelWidth">
              <el-input type="textarea" v-model="modulePostData.moduleDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="dialogbtn">
          <el-button @click="addApiModuleReset()">重置</el-button>
          <el-button @click="addApiModuleCancel()">关闭</el-button>
          <el-button type="primary" @click="addApiModuleSubmit()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查询服务模块 -->
    <el-dialog :title="queryDialogTitle" :visible.sync="queryDialogVisible" @close="queryDialogClose" width="900px">
      <el-form v-model="queryData">
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务模块名称" :label-width="formLabelWidth">
              <el-input v-model="queryData.moduleName" placeholder="请输入服务模块名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属模块" :label-width="formLabelWidth">
              <el-select v-model="queryData.gwEnvId" placeholder="请选择所属网关环境" popper-class="zIndex-popper">
                <el-option
                  v-for="item in getwayEnvData.list"
                  :key="item.gwEnvId"
                  :label="item.gwEnvName"
                  :value="item.gwEnvId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" :label-width="formLabelWidth">
              <el-select v-model="queryData.moduleStatus" placeholder="请选择当前状态" popper-class="zIndex-popper">
                <el-option
                  v-for="item in opts.moduleStatus"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="dialogbtn">
          <el-button @click="queryApiModuleReset">重置</el-button>
          <el-button @click="queryDialogClose">关闭</el-button>
          <el-button type="primary" @click="queryApiModuleSubmit()">查询</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import { VHeader } from '../../../../components'
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/ajax'
  import TopToolbar from '../../../../components/TopToolbar/TopToolbar'
  import setErrMsg from './com/setErrMsg.vue'
  import setMsgHeader from './com/setMsgHeader.vue'
  import modifyModule from './com/modifyModule.vue'
  import toDetail from './com/toDetail.vue'
  export default {
    name: 'a-p-i-module',
    components: {
      VHeader: VHeader,
      TopToolbar: TopToolbar,
      // 设置错误代码
      setErrMsg: setErrMsg,
      setMsgHeader: setMsgHeader,
      modifyModule: modifyModule,
      toDetail: toDetail
    },
    watch: {
      activeName (val) {
        switch (val) {
//          case 'first':
//            this.view = setErrMsg
//            break
//          case 'second':
//            this.view = setMsgHeader
//            break
          case 'third':
            this.view = modifyModule
            break
          case 'fourth':
            this.view = toDetail
            break
        }
      }
    },
    data () {
      return {
        dialogVisible: false,
        buttonsObj: [
          {
            text: '新增',
            oprType: 'addModule'
          },
          {
            text: '查询',
            oprType: 'queryModule'
          }
        ],
        formLabelWidth: '140px',
        // 查询服务模块
        queryDialogTitle: '',
        queryDialogVisible: false,
        ifQueryReset: false,
        queryDataCache: {},
        optionsServerType: [
          {
            id: '00',
            value: 'doubbo服务'
          },
          {
            id: '01',
            value: 'HTTP'
          }
        ],
        queryData: {
          gwEnvId: null,
          moduleName: null,
          moduleStatus: null
        },
        // tabs
        activeName: 'third',
        // tabs view
        view: 'modifyModule',
        // tabs data
        aliveShow: false,
        tabsData: '',
        tableData: {},
        // 网关环境LIST
        getwayEnvData: {},
        modulePostData: {},
        modulePostRules: {
          serverType: [
            {required: true, trigger: 'blur', message: '服务类型不能为空'}
          ],
          serverAddress: [
            {required: true, trigger: 'blur', message: '服务地址不能为空'}
          ],
            moduleCode: [
                {required: true, trigger: 'blur', message: '模块编号不能为空'}
            ],
            moduleName: [
                {required: true, trigger: 'blur', message: '模块名称不能为空'}
            ],
            moduleVersion: [
                {required: true, trigger: 'blur', message: '模块版本不能为空'}
            ],
            gwEnvId: [
                {required: true, trigger: 'change', message: '所属网关环境不能为空'}
            ]
        },
        // 服务模块状态 选项
        opts: {
          auditModel: [
            {name: '按模块开放', value: '00'},
            {name: '单独申请开放', value: '01'}
          ],
          transType: [
            {name: '原子交易', value: '0'},
            {name: '聚合系统', value: '1'},
            {name: '接入系统', value: '2'}
          ],
          opendIdTranslateFlag: [
            {name: '不转换', value: '0'},
            {name: '转换', value: '1'}
          ],
          orgJnlIdTranslateFlag: [
            {name: '不转换', value: '0'},
            {name: '转换', value: '1'}
          ],
          interfaceStatus: [
            {name: '待开放', value: '00'},
            {name: '已开放', value: '01'},
            {name: '已下线', value: '02'}
          ],
          moduleStatus: [
            {name: '创建待上线', value: '00'},
            {name: '已上线', value: '01'},
            {name: '已下线', value: '02'}
          ]
        },
        // 服务模块状态
        messages: {
          auditModel: {
            '00': '按模块开放',
            '01': '单独申请开放'
          },
          moduleStatus: {
            '00': '创建待上线',
            '01': '已上线',
            '02': '已下线'
          },
          interfaceStatus: {
            '00': '待开放',
            '01': '已开放',
            '02': '已下线'
          },
          transType: {
            '0': '原子交易',
            '1': '聚合系统',
            '2': '接入系统'
          },
          opendIdTranslateFlag: {
            '0': '不转换',
            '1': '转换'
          },
          orgJnlIdTranslateFlag: {
            '0': '不转换',
            '1': '转换'
          }
        },
        // 分页数据
        currentPage: 1,
        pageSize: 10
      }
    },
    methods: {
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'addModule':
            this.addModule()
                break
          case 'queryModule':
            this.queryModule()
                break
          default:
            break
        }
      },
      // 分页触发事件
      handleCurrentChange (e) {
        this.currentPage = e
        this.initializeData(e, this.pageSize)
      },
      handleSizeChange (e) {
        this.currentPage = 1
        this.initializeData(this.currentPage, e)
      },
      // 初始化数据
      initializeData (e = 1, s = 10) {
        ajax.post(api.LISTAPIMODULE + '?pageNum=' + e + '&pageSize=' + s, this.queryDataCache, true).then(res => {
          this.tableData = res
          this.$refs.table.setCurrentRow(this.tableData.list[0])
        }).catch(res => {})
      },
      // 格式化数据
      transData (row, column, cellValue, index) {
        let targetData = row[column.property]
        if (targetData) {
          return this.messages[column.property][row[column.property]]
        }
      },
      // 创建时间
      transCreateTime (row, column) {
        let time = row[column.property]
        if (time) {
          return this.transTime(time, 't')
        }
      },
      // 格式化数据结束
      apiMpduleDataReset () {
        this.modulePostData = {}
        this.$refs['modulePostForm'].resetFields()
      },
      // 新增服务模块
      addModule () {
        this.dialogTitle = '新增服务模块'
        this.dialogVisible = true
      },
      addApiModuleSubmit () {
          // 校验
          this.$refs['modulePostForm'].validate((valid) => {
              if (valid) {
                  if (!this.modulePostData.moduleDesc) {
                      this.modulePostData.moduleDesc = ''
                  }
                  ajax.post(api.ADDAPIMODULE, this.modulePostData, true).then(res => {
                      if (res === 'success') {
                          this.$message({
                              message: '新增服务模块成功',
                              type: 'success'
                          })
                          this.dialogVisible = false
                          this.dialogTitle = ''
                          this.apiMpduleDataReset()
                          this.currentPage = 1
                          this.initializeData()
                      }
                  }).catch(res => {
                      this.$message({
                          showClose: true,
                          message: res.errorMsg,
                          type: 'warning'
                      })
                  })
              } else {
                  return false
              }
          })
      },
      addApiModuleCancel () {
        this.dialogVisible = false
        this.dialogTitle = ''
        this.apiMpduleDataReset()
        this.$refs['modulePostForm'].resetFields()
      },
      addApiModuleReset () {
        this.apiMpduleDataReset()
      },
      // 查询服务模块
      queryModule () {
        this.queryDialogTitle = '查询服务模块'
        this.queryDialogVisible = true
        this.ifQueryReset = true
      },
      queryDialogClose () {
        // 不缓存查询的值
        this.queryData = {}
        this.queryDialogVisible = false
      },
      queryApiModuleReset () {
        this.queryData.moduleName = null
        this.queryData.moduleStatus = null
        this.queryData.gwEnvId = null
      },
      queryApiModuleSubmit () {
        this.ifQueryReset = false
        if (!this.queryData.moduleName) {
          this.queryData.moduleName = null
        }
        this.queryDataCache.gwEnvId = this.queryData.gwEnvId
        this.queryDataCache.moduleName = this.queryData.moduleName
        this.queryDataCache.moduleStatus = this.queryData.moduleStatus
        this.currentPage = 1
        this.initializeData()
        this.queryDialogVisible = false
        this.queryDialogTitle = ''
      },
      // API模块上线
      onlineApiModule (id, row) {
        ajax.post(api.ONLINEAPIMODULE, {moduleId: id}, true).then(res => {
          if (res === 'success') {
            this.$message({
              message: '上线成功',
              type: 'success'
            })
            row.moduleStatus = '01'
            // this.initializeData()
          }
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // API模块下线
      offlineApiModule (id, row) {
        ajax.post(api.OFFLINEAPIMODULE, {moduleId: id}, true).then(res => {
          if (res === 'success') {
            this.$message({
              message: '下线成功',
              type: 'success'
            })
            row.moduleStatus = '02'
            // this.initializeData()
          }
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // 列表 选中事件,获取tabs数据
      changeTabs (currentRow, oldCurrentRow) {
        if (currentRow) {
          this.aliveShow = true
        } else {
          this.aliveShow = false
        }
        this.tabsData = currentRow
        if (this.activeName === '0') {
          this.activeName = 'first'
        }
      },
      // 时间戳 => 时间 XXXX-XX-XX XX:XX:XX
      transTime (e, format) {
        switch (format) {
          case 't':
            let date = new Date(e)
            let moth = (date.getMonth() < 10) ? ('0' + (date.getMonth() + 1)) : date.getMonth()
            let day = (date.getDate() < 10) ? ('0' + date.getDate()) : date.getDate()
            let hours = (date.getHours() < 10) ? ('0' + date.getHours()) : date.getHours()
            let minutes = (date.getMinutes() < 10) ? ('0' + date.getMinutes()) : date.getMinutes()
            let seconds = (date.getSeconds() < 10) ? ('0' + date.getSeconds()) : date.getSeconds()
            return `${date.getFullYear()}-${moth}-${day}  ${hours}:${minutes}:${seconds}`
        }
      }
    },
    mounted () {
      this.initializeData()
      ajax.post(api.LIST_GATEWAY_ENV, {}, true).then(res => {
        this.getwayEnvData = res
      }).catch(res => {
        this.$message({
          showClose: true,
          message: res.errorMsg,
          type: 'warning'
        })
      })
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #api-module
    height 100%
    .main-cont
      padding:10px
      height calc(100% - 56px)
      overflow auto
      overflow-x hidden
    .el-table
      margin-top:10px
      width: 100%
      padding-left:10px
    .el-dialog
      .el-col
        padding:0 12px
      .el-pagination
        padding-top:20px
      .el-select
        display:block
        margin:0
      .dialogbtn
        text-align:right
</style>
